package org.finesys.common.log.trace.interceptor.forest;

import static org.finesys.common.log.constants.TraceConstants.FOREST_EXEC_AFTER;
import static org.finesys.common.log.constants.TraceConstants.FOREST_EXEC_BEFORE;
import static org.finesys.common.log.constants.TraceConstants.PARENT_ID;
import static org.finesys.common.log.constants.TraceConstants.SPAN_ID;
import static org.finesys.common.log.constants.TraceConstants.TRACE_ID;

import org.apache.poi.ss.formula.functions.T;
import org.finesys.common.log.trace.interceptor.AbstractInterceptor;
import org.finesys.common.log.trace.util.LogstashUtil;
import org.springframework.util.StringUtils;

import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;

import lombok.extern.slf4j.Slf4j;

/**
 * forest请求处置链路追踪id
 */
@Slf4j
public class TraceIdForestInterceptor extends AbstractInterceptor implements Interceptor<T> {


    @Override
    public boolean beforeExecute(ForestRequest request) {
        if (StringUtils.hasText(getTraceId())) {
            request.addHeader(TRACE_ID, getTraceId());
            request.addHeader(SPAN_ID, getSpanId());
            request.addHeader(PARENT_ID, getParentId());
            super.executeBefore(FOREST_EXEC_BEFORE);
        } else {
            if (log.isInfoEnabled()) {
                log.info(LogstashUtil.marker(), "current thread have not the traceId!");
            }
        }
        return true;
    }

    @Override
    public void afterExecute(ForestRequest request, ForestResponse response) {
        super.executeAfter(FOREST_EXEC_AFTER);
        if (log.isInfoEnabled()) {
            log.info(LogstashUtil.funcEndMarker(response.getContent()), "forest请求处理完毕");
        }
    }
}
